package com.soft.bams.server;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ATMServer extends JFrame {
    private CardLayout cardLayout = new CardLayout();
    private JPanel cardPanel = new JPanel(cardLayout);

    private ServerPanel serverPanel;
    private RankPanel rankPanel;

    private ServerSocket serverSocket;
    private ExecutorService threadPool;
    private boolean isRunning = false;

    public ATMServer() {
        initComponents();
        setupFrame();
        threadPool = Executors.newCachedThreadPool();
    }

    public void startServer() {
        try {
            serverSocket = new ServerSocket(8888);
            isRunning = true;
            JOptionPane.showMessageDialog(this,"服务已开启");
            new Thread(() -> {
                while (isRunning) {
                    try {
                        Socket socket = serverSocket.accept();
                        threadPool.execute(new ServerTasker(socket));
                    } catch (IOException e) {
                        if (isRunning) {
                            JOptionPane.showMessageDialog(this,"服务器异常");
                        }
                    }
                }
            }).start();
        } catch (IOException e) {
           JOptionPane.showMessageDialog(this,"服务器启动失败"+e.getMessage());
        }
    }

    public void stopServer() {
        isRunning = false;
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
            threadPool.shutdown();
            JOptionPane.showMessageDialog(this,"服务器已关闭");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this,"服务器关闭异常");
        }
    }

    private void initComponents() {
        serverPanel = new ServerPanel(this);
        rankPanel = new RankPanel(this);

        cardPanel.add(serverPanel, "Server");
        cardPanel.add(rankPanel, "Rank");

        this.add(cardPanel);
    }

    private void setupFrame() {
        this.setTitle("ATM服务端");
        this.setSize(800, 600);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
    }

    public void showPanel(String panelName) {
        cardLayout.show(cardPanel, panelName);
    }

    public static void main(String[] args) {
            new ATMServer().setVisible(true);

    }
}
